package org.ssssssss.magicapi.mqtt;

import net.dreamlu.iot.mqtt.codec.ByteBufferUtil;
import net.dreamlu.iot.mqtt.core.client.MqttClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * 客户端测试
 *
 */
public class MqttClientSync {
	private static final Logger logger = LoggerFactory.getLogger(MqttClientSync.class);
	private static MqttClient client=null;
	
	// 连接服务器
	public static boolean connect(String ip,int port,String name,String pwd) {
		if(client!=null&&client.isConnected()) {
			return true;
		}
		else {
			client = MqttClient.create()
				.ip("127.0.0.1")
				.port(1883)
				.username("mica")
				.password("mica")
				.connectListener(new MqttClientConnectListener())
				// 同步连接，注意：连接会阻塞
				.connectSync();	
			if(client!=null) {
				return true;
			}
		}
		return false;
	}
	// 订阅主题
	public static void subscribe(String topicName) {
		client.subQos0(topicName, (topic, payload) -> {
			logger.info(topic + '\t' + ByteBufferUtil.toString(payload));
		});		
	}
	// 取消订阅主题
	public static void unSubscribe(String topicName) {
		client.unSubscribe(topicName);
	}
	// 发布消息
	public static boolean publish(String topic,String msg) {
		return client.publish(topic, msg.getBytes(StandardCharsets.UTF_8));
	}
	// 发布字节流消息
	public static boolean publish(String topic,byte[] msg) {
		return client.publish(topic, msg);
	}
	
	
	public static void main(String[] args) {
		// 初始化 mqtt 客户端
		MqttClient client = MqttClient.create()
			.ip("127.0.0.1")
			.port(1883)
			.username("mica")
			.password("mica")
			.connectListener(new MqttClientConnectListener())
			// 同步连接，注意：连接会阻塞
			.connectSync();

		client.subQos0("/test/#", (topic, payload) -> {
			logger.info(topic + '\t' + ByteBufferUtil.toString(payload));
		});

		client.unSubscribe("/test/#", "/test/123");

		// 连接上之后发送消息，注意：连接时出现异常等就不会发出
		client.publish("/test/client", "mica最牛皮".getBytes(StandardCharsets.UTF_8));
	}
}
